App.require(function () {
    var app = App.getCurrent();
    var createUid = (function () {
        var uid = 0;
        return function () {
            return "scene" + uid++;
        }
    }());

    app.defineComponent("pre-scene-manager", {
        getDomObj: function () {
            this.attachDom(".scene-container", "container")
                .attachDom("#sceneList", "sceneList")
                .attachEvent("sceneList", "click", this.clickSceneListHandler, false)
                .attachEvent("container", "iconclick", this.iconClickHandler, false)
        },
        clickSceneListHandler: function (ev) {
            var target = ev.target, dom = Component.getNodeName(target, "DIV");
            var uid = dom.dataset.id;
            if (uid) {
                var obj = this._getSceneObjByUid(uid);
                if (obj && obj.index !== this.data.currentIndex) {
                    this.data.currentIndex = obj.index;
                    this.dispatchCustomEvent("itemclick", { index: obj.index, scene: obj.scene });
                }
            }
        },
        _getSceneObjByUid: function (uid) {
            var scenes = this.domList.scenes;
            for (var i = 0; i < scenes.length; i++) {
                if (scenes[i].uid == uid) return {
                    index: i, scene: scenes[i]
                }
            }
        },
        iconClickHandler: function (ev) {
            var action = ev.detail.component.dataset.action;
            switch (action) {
                case "close": 
                    var dom = Component.getNodeName(ev.detail.event.target, "DIV");
                    this.removeScene(dom, dom.dataset.id);
                    var activeScene = this.domList.scenes[this.data.currentIndex];
                    this.dispatchCustomEvent("scenedelete", {
                        uid: dom.dataset.id,
                        activeScene: activeScene
                    })
                    
                    this.domList.scenes.splice(this.data.currentIndex, 1);
                    if (this.domList.scenes.length == 1) {
                        this.data.currentIndex = undefined;
                    }
                    else if (this.data.currentIndex != 0) {
                        this.data.currentIndex--;
                    }
                    break;
                case "plus": 
                    this.dispatchCustomEvent("sceneObjplus", {
                        component: this, event: ev
                    });
                    break;
            }

        },
        removeScene: function (dom, uid) {
            var scenes = this.domList.scenes;
            for (var i = scenes.length - 1; i >= 0; i--) {
                if (scenes[i].uid == uid) {
                    if (i <= this.data.currentIndex) this.data.currentIndex--;
                    scenes[i].parent = null;
                    scenes.splice(i, 1);
                    dom.remove();
                    break;
                }
            }
        },
        addSceneByName: function (name, description) {
            this.addScene({
                uid: createUid(),
                title: name,
                description: description,
                scenes: [],
                url: ""
            });
        },
        saveScenes: function (scenes, url) {
            this.domList.scenes[this.data.currentIndex].url = url;
            this.domList.scenes[this.data.currentIndex].scenes = scenes;
            this.domList.sceneList.children[this.data.currentIndex].lastElementChild.src = url;
        },
        addScene: function (scene) {
            var that = this;
            this.insertAdjacentHTML(this.domList.sceneList, this.data.itemHtml, "beforeend", function () {
                that.data.currentIndex = that.domList.sceneList.children.length - 1;
                that.domList.scenes[that.data.currentIndex] = scene;
            }, { scene: {
                uid: scene.uid,
                title: scene.title,
                description: scene.description,
                url: scene.url
            } })
        },
        saveScene: function (scene) {
            if (typeof this.data.currentIndex !== "undefined") {
                var item = this.domList.sceneList.children[this.data.currentIndex];
                var currentScene = this.domList.scenes[this.data.currentIndex];
                currentScene.data = scene;
                currentScene.url = scene.url;
                item.firstElementChild.textContent = currentScene.title;
                item.lastElementChild.src = scene.url;
            }
        },
        getScenes: function () {
            return this.domList.scenes;
        },
        getSceneList: function (bk) {
            var scenes = this.domList.scenes, len = scenes.length, result = [];
            scenes.forEach(function (scene, index) {
                scene.toObject(function (obj) {
                    result[index] = obj;
                    if (--len === 0) bk(result);
                })
            });
        },
        render: function (next) {
            this.domList.scenes = [];
            this.data.currentIndex = undefined;
            this.fetchAll(["./item.html", "./index.html"], function (textArray) {
                this.data.itemHtml = textArray[0];
                return next(this.renderHTML(textArray[1].replace("{{{itemHTML}}}", textArray[0])));
            })
        },
        get isReady() {
            return typeof this.data.currentIndex === "undefined";
        },
        filter: {
            imgurl: function (src) {
                return src || "/public/img/1.png";
            }
        }
    });
});